/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package hibernatedaos;

import hibentities.Product;
import hibentities.Purchase;
import hibentities.PurchaseDetail;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author piotrek
 */
@Repository
public class PurchaseHibernateDao{

	private SessionFactory sessionFactory;
	private HibernateTemplate hibernateTemplate;

	public PurchaseHibernateDao(){

	}
	
	@Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {

		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
		
    }

	/**
	 * Pobierz dane zakupu
	 * @param id
	 * @return Purchase
	 */
	public Purchase getPurchase( Long id ){

		return this.hibernateTemplate.get(Purchase.class, id);
		
	}


	/**
	 * Dodawanie nowego zakupu przez Jdbc, z kosztami przesylki - test bufora 1 poziomu
	 * @return
	 */
	public boolean addPurchaseWithShipment( Purchase purchase ){

		Session s = this.hibernateTemplate.getSessionFactory().openSession();
		Transaction t = s.beginTransaction();
		s.save(purchase);
//		this.hibernateTemplate.save( purchase );

		/**
		 * Policz ilosc zakupow i wstaw odpowiednia kwote do purchase i produkt z liczba do purchase details
		 */
		int numOfProducts = purchase.getPurchaseDetails().size();

		purchase.setCost( purchase.getCost() + (10*numOfProducts));

		PurchaseDetail pd = new PurchaseDetail();
		pd.setAmount(numOfProducts);
		pd.setProduct( (Product) s.get( Product.class, Long.parseLong("42") ));
		purchase.getPurchaseDetails().add( pd );

		s.update(purchase);
		
		t.commit();
		s.close();

		return true;

	}

	/**
	 * Dodawanie nowego zakupu przez Hibernate
	 * @return
	 */
	public boolean addPurchase( Purchase purchase ){

		this.hibernateTemplate.save( purchase );

		return true;

	}

	/**
	 * Update danych zakupu
	 * @param purchase
	 * @return
	 */
	public boolean updatePurchase( Purchase purchase ){

		this.hibernateTemplate.update( purchase );

		return true;

	}

	/**
	 * Update danych zakupu
	 * @param purchase
	 * @return
	 */
	@Transactional
	public boolean updateTransactionalPurchase( Purchase purchase ){

//		Session s = this.hibernateTemplate.getSessionFactory().openSession();
//		Transaction t = s.beginTransaction();
//		s.update(purchase);
		this.hibernateTemplate.update( purchase );
//		t.commit();
//		s.close();

		return true;

	}
}
